/**
 * @file index.tsx
 * @description 待配送列表（主页）
 */
import React, {useState, useEffect} from 'react';
import { Modal as RNModal, Linking, View, ImageBackground,BackHandler,Alert, } from 'react-native';
import {AnyIfEmpty, useDispatch, useSelector} from 'react-redux';
import rootReducer from '../../redux/reducers';
import { Box, FlatList, ScrollView, HStack, VStack, Text, Spacer, Center, Button,useToast,Spinner,} from 'native-base';
import HeaderScreen from '../../components/header';
import StateScreen from "../../components/stateScreen";
import {useFocusEffect} from '@react-navigation/native';
import storage from '../../utils/storage';
import {useMount} from 'ahooks';
import {setUserInfo} from '../../redux/reducers/userReducer';
import {setDispatchingList,clearDispatchingList} from '../../redux/reducers/dispatchingReducer';
import {isEmpty,deepCopy,} from '../../utils/untils';
import { scaleSize, } from "../../utils/screenUtil";
import * as request from "../../request/common";
import { ListRenderItem } from 'react-native';
import * as Device from "../../utils/device";
import GlobalEmitter from "../../utils/global";
import { PermissionsAndroid } from 'react-native';


import Hotupdate from 'react-native-update';
import RNFS from 'react-native-fs';
import RNFetchBlob from "rn-fetch-blob";
import PercentageCircle from 'react-native-percentage-circle';

let loadMoreTimer: any = null;
let lastBackPressed: any = null;
let hotUpdate = false;
const HomeScreen: React.FC<ComponentProp> = ({navigation,route }) => {
  // 变量
  const [page, setPage] = useState(1); // 当前页码
  const [limit, setLimit] = useState(10); // 页面大小
  const [refreshing,setRefreshing] = useState(false); // 刷新状态 
  const [showNoResult, setShowNoResult] = useState(false); // 无数据
  const [showNoMore, setShowNoMore] = useState(false); // 没有更多信息
  const [showLoadMore, setShowLoadMore] = useState(false); // 正在加载数据
  const [total, setTotal] = useState(); // 总数
  const toast = useToast();
  const [search,setSearch] = useState(""); // 查询关键字
  const [departOrderId,setDepartOrderId] = useState(""); // 已发车订单id
  const [modalVisible,setModalVisible] = useState(false); // modal 是否显示
  const [modalTransparent,setModalTransparent] = useState(false); // modal 背景是否透明
  const [modalContent,setModalContent] = useState(""); // modal 更新类型
  const [downloadProgress,setDownloadProgress] = useState(0); // 下载进度
  const [hotProgress,setHotProgress] = useState(0); // 热更进度
  const [updateInfo,setUpdateInfo] = useState<any>({}); // 更新信息

  // redex
  const userInfo: any = useSelector(
    (state: ReturnType<typeof rootReducer>) => state?.userInfo?.user,
  );
  const dispatchingList = useSelector(
    (state: ReturnType<typeof rootReducer>) => state?.dispatching?.dispatching,
  );
  const dispatch = useDispatch();

  /*********生命周期************/
  useMount(async () => {
    console.log('初始化完成！！！！');
    GlobalEmitter.on("logoutClearDispatchingList", () => { // 退出后清空待配送列表
      dispatch(setDispatchingList([]));
    });
    GlobalEmitter.on("updateOrderStatus5000", ({ codeId }) => { // 发货后移除列表单子
      setDepartOrderId(codeId);
    });

   

  });


  
 //****更新*******/

 /**
  * 检测更新
  */
const checkUpdate = async() => {

  const readGranted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE);
  //OR
  const writeGranted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE);
  // For both, you can use as below and get as response the status in an array for each permission requested
  const result = await PermissionsAndroid.requestMultiple([
      PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
      PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
    ]);
  const isGranted = result[PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE] === 'granted' 
          && result[PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE] === 'granted';




  request.getAppVersion().then((response: any) => {
    if (response?.statusCode == 1) {
      if (Number(Device.appVersion.replace(/\./g, "0")) < response.data.version) { // 原生更新
        setModalVisible(true)
        setUpdateInfo(response?.data);
        setModalContent("update")
        // checkHotUpdate(true,true,response?.data);
      } else {
        checkHotUpdate(true,true,response?.data);
      }

    }
  });
};
/**
 * 更新应用
 * @returns 
 */
const updateApplication = () => {
  return Device.platform == "ios" ? Linking.openURL(updateInfo.ios_download_url) : downloadApkFile(updateInfo.android_download_url);
};
/**
 * 下载apk
 * @param url 原生安卓url
 */
const downloadApkFile = async (url: string) => {
 // 下载apk文件
 debugger;
 const filePath = `${RNFS.DocumentDirectoryPath}/release.apk`;
 const fileExists = await RNFS.exists(filePath).then((exists) => exists).catch(() => false);
 if (fileExists) {
   await RNFS.unlink(filePath);
 }
 setModalTransparent(true);
 setModalContent("downloading");
 setModalVisible(true);

//  let progress: any = 0;
//  const options = {
//    fromUrl: url,
//    toFile: filePath,
//    background: true,
//    progress: (res: any) => {
//     debugger;
//      progress = parseInt((res.bytesWritten / res.contentLength) * 100);
//      if (progress != downloadProgress) {
//       setDownloadProgress(progress);
//      }
//    }
//  };
//  RNFS.downloadFile(options).promise.then((response) => {
//   debugger;
//    RNFetchBlob.android.actionViewIntent(filePath, 'application/vnd.android.package-archive');
//  });
//设置下载参数
const options = {
  fromUrl: url,
  toFile: filePath,
  background: true,
  progressDivider: 5,
  begin: (res: any) => {
    //开始下载时回调
    // debugger;
    console.log('begin', res);
  },
  progress: (res: any) => {
    //下载过程中回调，根据options中设置progressDivider:5，则在完成5%，10%，15%，...，100%时分别回调一次，共回调20次。
    // debugger;
    console.log('progress', res)
    let progressNumber = parseInt((res.bytesWritten / res.contentLength) * 100);
    setDownloadProgress(progressNumber);
  }
}
const ret = RNFS.downloadFile(options);//调用downloadFile开始下载
console.log(ret.jobId); //打印一下看看jobId
ret.promise.then((res: any)=>{
  debugger;
  RNFetchBlob.android.actionViewIntent(filePath, 'application/vnd.android.package-archive');
}).catch((ee: any)=>{
  let aa = ee;

  debugger;
})





}

/**
 * 检测热更
 * @param reload 重新加载
 * @param force 是否强制更新
 * @param updateInfo 更新信息
 */
const checkHotUpdate = async (reload:boolean,force = false,updateInfo: any) => {
  if (force !== true && Device.platform == "ios") { // TODO 屏蔽ios 审核账号 jiangsu
    if (!userInfo || userInfo?.user_id == undefined || parseInt(userInfo?.user_id) == 126) {
      return false;
    }
  }
  let serverHotUpdateVersion = updateInfo.hot_update || 1;
  let hotUpdateVersion: any = await storage.load({ key: "hotUpdateVersion" }).then((version) => parseInt(version)).catch(() => 1);
  let bundleFileExists = await Hotupdate.bundleFileExists().then((exists: any) => exists).catch(() => false);
  serverHotUpdateVersion = parseInt(serverHotUpdateVersion);
  hotUpdateVersion = parseInt(hotUpdateVersion);
  if ((hotUpdateVersion < serverHotUpdateVersion) || !bundleFileExists) {
    createHotUpdateTask(serverHotUpdateVersion, (result: any) => {
      if (modalVisible) {
        setModalVisible(false);
        setModalContent("");
        if(result && reload) {
          Hotupdate.reloadJSBundle();
        }
      } else {
        if (result && reload) {
          setModalVisible(false);
          setModalContent("");
          Hotupdate.reloadJSBundle();
        }
      }
    });
  }
};

/**
 * 创建热更任务
 * @param serverHotUpdateVersion 服务端热更版本
 * @param callback 回调
 */
const createHotUpdateTask = (serverHotUpdateVersion: any, callback: any) => {
  if(hotUpdate){
    return;
  }
  let progressNumber = 0;
  // const jsbundleZipDownloadUrl = `https://api.fangxinjia.cn/app/sd_factory/${Device.platform}_${Device.appVersion}.zip`;
  const jsbundleZipDownloadUrl = `https://api.fangxinjia.cn/app/sd_factory/${Device.platform}_2.1.0.zip`; // _${Device.appVersion}.zip
  Hotupdate.downloadJSBundleFromServer(jsbundleZipDownloadUrl, (progress: any) => {
    hotUpdate = true;
    if(progress  > progressNumber){
      progressNumber = progress;
    }else{
      progress = progressNumber;
    }
    if(!modalVisible){
      setModalContent("hotupdate");
      setModalTransparent(true);
      setModalVisible(true);
      setHotProgress(progress);
    }
    if(progress > 100){
      setModalVisible(false);
      setModalContent("");
    }
    setHotProgress(progress);
  },(result: any) => {
    storage.save({ key: "hotUpdateVersion", data: serverHotUpdateVersion }).finally(() => {
      callback(result.status);
      hotUpdate = false;
    });
  })
};





  // 用户是否登录
  const checkUserIsLogin = async () => {
    let localUserInfo = userInfo;
    console.log(localUserInfo);
    if (isEmpty(localUserInfo)) {
      let storageUserInfo = await storage.load({ key: "userInfo" }).then((user) => user).catch(() => {}) || {};
      if (isEmpty(storageUserInfo)) {
        Alert.alert(
          '提示',
          '您好,当前未登录,请登录后使用',
          [
            {
              text: '登录',
              onPress: () => {
                navigation && navigation.navigate('Login');
              },
            },
          ],
          {cancelable: false},
        );
      } else {
        dispatch(setUserInfo(storageUserInfo));
        // checkUpdate();
      }
    }else{
      // checkUpdate();
    }
  };

  /**
   * 处理安卓返回
   */
  const handleBackPress = () => {
    if (lastBackPressed && lastBackPressed + 2000 >= Date.now()) {
      return false;
    }
    lastBackPressed = Date.now();
    toast.show({
      placement: "top",
      description: '再点击一次退出应用',
    });
    return true;
  };

  /**
   * 导航获取焦点、失去焦点
   */
  useFocusEffect(
    React.useCallback(() => {
      console.log('屏幕获取焦点');
      if (Device.platform == "android") {
        BackHandler.addEventListener('hardwareBackPress', handleBackPress);
      }
      checkUserIsLogin();
      return () => {
        if (Device.platform == "android") {
          BackHandler.removeEventListener('hardwareBackPress', handleBackPress);
        }
      };
    }, []),
  );


  const handleSearch = (search?: string) => {
    console.log(search);
    setSearch(search || '');
  };

  useEffect(()=>{
    refreshPage(); 
  },[search])

  useEffect(() => { //  用户从无到有赋值，则刷新列表
    if (!isEmpty(userInfo)) {
      if (dispatchingList?.length == 0) {
        refreshPage();
      }
    }
  }, [userInfo]);

  useEffect(() => { //  用户从无到有赋值，则刷新列表
    if (dispatchingList?.length > 0 && departOrderId.length >0) {
      // 移除已发车订单
      let list = deepCopy(dispatchingList);
      let findIndex = list.findIndex((item: any) => item.code_id == departOrderId);
      if(findIndex != -1){
        list.splice(findIndex,1);
        dispatch(setDispatchingList(list));
      }
      setDepartOrderId("");
    }
  }, [departOrderId]);

  /**
   * 刷新数据
   */
  const refreshPage = () => {
    if(isEmpty(userInfo)){
      return;
    }
    setRefreshing(true);
    let nextPage = 1;
    setPage(nextPage);
    request.getDispatchingList(nextPage,limit,search).then((res: any) => {
      if (res?.code == 40020) {
       dispatch(setDispatchingList(res?.data?.list));
       setRefreshing(false);
       setTotal(res?.data?.total);
       setShowNoMore(res?.data?.list?.length < limit ? true : false);
       setShowNoResult(res?.data?.list?.length == 0 ? true : false);
      } else {
        setRefreshing(false);
        setShowNoResult(true);
      }
    });
  }

  /**
   * 加载数据
   */
  const onEndReached = () => {
    if(isEmpty(userInfo)){
      return;
    }
    if(refreshing || showNoMore || dispatchingList?.length == 0 || loadMoreTimer ){ // 正在请求、没有更多、数据为空 不再继续请求
      return;
    }
    loadMoreTimer = setTimeout(() => {
      setRefreshing(true);
      setShowLoadMore(true);
      let nextPage = page + 1;
      setPage(nextPage);
      request.getDispatchingList(nextPage,limit,search).then((res: any) => {
        if (res?.code == 40020) {
        let allList: any = [...dispatchingList,...res?.data?.list];
        dispatch(setDispatchingList(allList));
         setRefreshing(false);
         setTotal(res?.data?.total);
         setShowLoadMore(false);
         setShowNoMore(res?.data?.list?.length < limit ? true : false);
        } else {
          setRefreshing(false);
          setShowNoMore(false);
          setShowLoadMore(false);
        }
        loadMoreTimer = null;
      });
    });
  }

  // 渲染列表
  const handleRenderItem: ListRenderItem<any>= (ListItem: any)=> {
    let {index,item} = ListItem;
    return(<Box
    flex={1}
    borderBottomWidth="0.3"
    borderColor="muted.300"
    ml={['4', '4']}
    mr={['4', '4']}
    py="2"
    >
    <HStack  flex={1} w='100%'  justifyContent="space-between" >
      <VStack w='80%' textAlign="left" space="0.5" pl="0"  >
        <Text color="coolGray.800" bold>
        {item?.code_id}
        </Text>
        <Text color="coolGray.600">
        {item?.address_detail}
        </Text>
        <Text color="coolGray.600" >
          司机:<Text bold>{item?.driver_name}{item?.driver_mobile? "，"+item?.driver_mobile: ''}</Text>
        </Text>
      </VStack>
      <Spacer />
      <Center w='20%'>
      <Button bg="#4F94F9" size="sm" _pressed={{ bg:"#4F94F9" }} onPress={() => {
        if(isEmpty(item.driver_name)){
          toast.show({
            placement: "top",
            description:'请先安排司机'
          });
          return;
        }
        navigation?.navigate('DispatchingDetailsScreen',{
          orderInfo: item,
        })
      }}>去发车</Button>
      </Center>
  
    </HStack>
  </Box>)
  }

  const renderListFooter = () => {
    if(dispatchingList?.length > 0 ){
      if (showNoMore) {
        return <Center  py="2" ><Text color="#d4d4d4">没有更多数据了...</Text></Center> ;
      } else if (showLoadMore) {
        return <Center py="2" ><Spinner color="cyan.500" /></Center>;
      }
    }
    return null;
  };

  return (
    <Box bg="gray.100" borderRadius="md" w="100%" h="100%">
      <HeaderScreen
        leftBtn={false}
        search={true}
        searchTitle="请输入地址/单号查询"
        parentMethod={handleSearch}
        navigation={navigation}></HeaderScreen>
      <FlatList
        data={dispatchingList}
        onEndReachedThreshold={Device.platform == "ios" ? 0 : 1}
        onEndReached={onEndReached}
        refreshing={refreshing}
        onRefresh={refreshPage}
        initialNumToRender={limit}  // 初始化大小
        renderItem={handleRenderItem}
        ListFooterComponent={renderListFooter}
        keyExtractor={(item: any) => item?.code_id}
        ListEmptyComponent={<StateScreen></StateScreen>}
      />
          <RNModal
          animationType="fade" // 淡入淡出
          transparent={true} // 属性是指背景是否透明
          hardwareAccelerated={true} 
          presentationStyle="overFullScreen"
          visible={modalVisible}
          onRequestClose={()=>{
            debugger;
          }}
        > 
        {modalContent == "update" ? (
            <View
              style={{
                flex: 1,
                backgroundColor: "rgba(0,0,0,0.6)",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <View style={{
                 width: Device.deviceWidth * 0.8,
                 height: scaleSize(856),
                 borderRadius: 8,
                 overflow: "hidden",
                 backgroundColor: "transparent",
                 position: 'relative'
              }}>
                <ImageBackground
                  style={{
                    position: "absolute",
                    left: 0,
                    right: 0,
                    top: 10,
                    bottom: 0
                  }}
                  source={require("../../images/221525940662_.pic_hd.jpg")}
                ></ImageBackground>
                <ScrollView  mt="240" mb="44" p="4" >
                {updateInfo.content.map((item: any, index: number) => {
                    return (
                      <Text
                      color="#333333"
                        key={index}
                      >
                        {index + 1}、{item}
                      </Text>
                    );
                  })}
                </ScrollView >
                <View style={{
                    height: 44,
                    position: "absolute",
                    left: 0,
                    right: 0,
                    bottom: updateInfo.is_force == 1 ? 0 : -2,
                    zIndex: 10,
                    flexDirection: "row",
                    justifyContent: "space-around",
                    alignItems: "center"
                }}>
                  {updateInfo?.is_force == 1 ? (
                   <Button
                   variant="outline"
                   w="48%"
                   bg="#ffffff"
                   _text={{
                    color:'#333333'
                   }}
                   _pressed={{
                    color:'#333333',
                    bg:"#ffffff"
                   }}
                   onPress={()=>{
                    setModalVisible(false);
                    setModalTransparent(true);
                    setModalContent("");
                  }}
                 >
                  下次再说
                 </Button>
                  ) : null}
                  <Button
                     w={updateInfo?.is_force == 1 ? "48%":"100%"}
                     bg="#ff550b"
                     _pressed={{
                      bg:"#ff550b"
                     }}
                    onPress={updateApplication}
                  >
                立即更新
                  </Button>
                </View>
              </View>
            </View>
          ) : null}
          {
            modalContent == "downloading" ?
              <View style={{ flex: 1, backgroundColor: 'rgba(0,0,0,0.6)', alignItems: 'center', justifyContent: 'center' }}>
                <Text style={{
                  fontSize: 14,
                  color: "#ffffff",
                  alignSelf: "center",
                  marginBottom: 20
                }}>正在下载放心家全屋定制更新包，请稍后...</Text>
                <PercentageCircle
                  radius={65}
                  percent={downloadProgress}
                  color={"#f498db"}>
                </PercentageCircle>
              </View>
              :
              null
          }
          {modalContent == "hotupdate" ? (
            <View
              style={{
                flex: 1,
                backgroundColor: "#ffffff",
                alignItems: "center",
                justifyContent: "center",
                position: "relative",
              }}
            >
              <ImageBackground
                source={require("../../images/101564729594_.pic_hd.jpg")}
                style={{
                  position: "absolute",
                  left: 0,
                  top: 0,
                  right: 0,
                  bottom: 0,
                }}
              ></ImageBackground>
              <View
                style={{
                  width: "90%",
                  height: 100,
                  borderRadius: 4,
                  flexDirection: "column",
                  justifyContent: "center",
                  alignItems: "center",
                  backgroundColor: "#ffffff",
                  shadowOffset: {
                    width: 0,
                    height: 5,
                  },
                  shadowOpacity: 0.25,
                  shadowRadius: 5,
                  shadowColor: "#ea4f26",
                  elevation: 1,
                }}
              >
                <Text
                  style={{
                    fontSize: 14,
                    color: "#333333",
                    alignSelf: "center",
                    marginBottom: 20,
                  }}
                >
                  正在更新，已完成{hotProgress}%
                </Text>
                {/* <ProgressBar
                  fillStyle={{ backgroundColor: "#4F94F9" }}
                  backgroundStyle={{
                    backgroundColor: "#cccccc",
                    borderRadius: 2,
                  }}
                  style={{
                    marginTop: 10,
                    width: parseInt(Device.deviceWidth * 0.6),
                  }}
                  progress={this.state.hotProgress / 100}
                /> */}
              </View>
            </View>
          ) : null}
        </RNModal>
    </Box>
  );
};

export default HomeScreen;
